﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspNetCoreRateLimit;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using PSAMMatrixCloud.Model;

namespace PSAMMatrixCloud.WebAPI
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            // 需要从appsettings.json中加载配置
            services.AddOptions();
            var EMailConfig = Configuration.GetSection("EMailConfig");
            Model.EMailConfigModel.MailServer=   EMailConfig["MailServer"];
            Model.EMailConfigModel.MailAuthPass = EMailConfig["MailAuthPass"];
            Model.EMailConfigModel.MailAuthUser = EMailConfig["MailAuthUser"];

            var ConnetionConfig = Configuration.GetSection("ConnectionStrings");
            ConnectionStrings.PSAM = ConnetionConfig["PSAM"];
            // 存储IP计数器及配置规则
            services.AddMemoryCache();
            services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
            services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
            services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

            // 按照文档，这两个是3.x版的breaking change，要加上
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseCors(builder => builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
            app.UseIpRateLimiting();
            app.UseBussinessRequestMiddleware();
            app.Run(async (context) =>
            {
                
            });
        }
    }
}
